#!/usr/bin/env bash
#-------------------------------------------------------
#	FileName	: ice.sh
#	Author		：hpy
#	Date		：2022年08月06日
#	Description	：iCESugar-nano 工具链管理脚本
#-------------------------------------------------------
cd $(dirname $0)
shell_name=$(basename $0)


if [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]] || [[ "$1" == "-help" ]]  || [[ "$1" == "help" ]] ; then 
cat<<EOF
$(basename $0) -v 1.0 
iCESNano FPGA开发板工具
Usage: $(basename $0) [option] [filename]			
    $(basename $0) build [filename]         综合,filename为顶层文件名称
    $(basename $0) prog                     将当前路径下的bin文件下载到icesugar开发板中
    $(basename $0) filename                 综合filename文件并下载到硬件中去 
    $(basename $0) time                     时序分析
    $(basename $0) clean                    清除生成的文件
    $(basename $0) help/-h                  显示使用帮助
示例
	$(basename $0) build top.v 
EOF
exit 0
fi 

function main(){
    # test ! -f $1 && echo "不存在 $1 文件" | cat && exit

    case $1 in 
        build) build $2 ;;
        prog) prog ;;
        time) micetime ;;
        clean)clean_f ;; 
        *.v) clean_f && build $1 && prog ;;  
        *) ;;
    esac 
}



#termux down fpga bin
function prog() {
    echo ""
    echo "INFO:start write bin to FPGA"
#	termux-setup-storage 
	am broadcast --user 0 --es com.termux.app.reload_style storage -a com.termux.app.reload_style com.termux > /dev/null

    local src=$(ls ~/storage/)
	for i in $src 
	do
		if [[ $i == "external-"* ]] ; then 
			echo $i
			cp *.bin ~/storage/$i/top.bin 
		fi 
		#cp *.bin $i/top.bin 
	done 
	echo "fpga bin file have been copy to fpga board!"
}

# 综合  , 输入为顶层文件
function build() {
    test ! -f $filename && echo "info:$filename文件不存在" |cat && exit
    filename=$(basename $1)
    filename=$(echo $filename|cut -d . -f1)
    
    pcf_file=$(ls *.pcf) 
    test $? -ne 0 && echo "info:IO约束文件 *.pcf 文件不存在" |cat && exit

    yosys -p "synth_ice40 -blif ${filename}.blif" ${filename}.v
	#nextpnr-ice40 --lp1k --package cm36 --json $(filename).json --pcf $(pcf_file) --asc $(filename).asc --freq 48
	arachne-pnr -d 1k -P cm36 -p ${pcf_file}  ${filename}.blif -o ${filename}.asc
	icepack ${filename}.asc ${filename}.bin

}

function clean_f() {
    rm -rf *.blif *.asc *.bin
}

#时序分析
function micetime() {
    ls *.v
    test $? -ne 0 && echo "info:*.asc 文件不存在" |cat && exit
    icetime -tmd lp1k *.asc
}


main $*
